#include "Frustum.h"
#include "Node.h"

Frustum::Frustum()
{
}
Frustum::~Frustum()
{
}

bool Frustum::FrustumCollision(Node* a_pNode)
{
	//Get the width of the node
	float width = a_pNode->GetAABB().GetMax().x - a_pNode->GetAABB().GetMin().x;	

	//Loop through all planes of the frustum
	for(int i=0; i<6; ++i)
	{
		//Check if its inside on the left side
		if(D3DXPlaneDotCoord(&m_planes[i], &a_pNode->GetAABB().GetMin()) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the right side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMin().x + width, a_pNode->GetAABB().GetMin().y, a_pNode->GetAABB().GetMin().z)) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the top side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMin().x, a_pNode->GetAABB().GetMin().y + width, a_pNode->GetAABB().GetMin().z)) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the bottom side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMin().x, a_pNode->GetAABB().GetMin().y, a_pNode->GetAABB().GetMin().z + width)) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the near side
		if(D3DXPlaneDotCoord(&m_planes[i], &a_pNode->GetAABB().GetMax()) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the far side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMax().x - width, a_pNode->GetAABB().GetMax().y, a_pNode->GetAABB().GetMax().z)) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the far side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMax().x, a_pNode->GetAABB().GetMax().y - width, a_pNode->GetAABB().GetMax().z)) >= 0.0f)
		{
			continue;
		}
		//Check if its inside on the far side
		if(D3DXPlaneDotCoord(&m_planes[i], &D3DXVECTOR3(a_pNode->GetAABB().GetMax().x, a_pNode->GetAABB().GetMax().y, a_pNode->GetAABB().GetMax().z - width)) >= 0.0f)
		{
			continue;
		}
		//If it did not pass any of the above checks, it's outside that plane, no way a collision can occur
		return false;				
	}
	//If it makes it through the entire loop then the node is inside the frustum, return true
	return true;

}
void Frustum::Setup(D3DXPLANE a_left, D3DXPLANE a_right, D3DXPLANE a_top, D3DXPLANE a_bottom, D3DXPLANE a_near, D3DXPLANE a_far)
{
	//Setup and normalize all 6 planes of the frustum
	m_planes[0] = *D3DXPlaneNormalize(&a_left, &a_left);
	m_planes[1] = *D3DXPlaneNormalize(&a_right, &a_right);
	m_planes[2] = *D3DXPlaneNormalize(&a_top, &a_top);
	m_planes[3] = *D3DXPlaneNormalize(&a_bottom, &a_bottom);
	m_planes[4] = *D3DXPlaneNormalize(&a_far, &a_far);
	m_planes[5] = *D3DXPlaneNormalize(&a_near, &a_near);
}